package com.tlgen.coopera.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tlgen.coopera.model.RegistryServer;
import com.tlgen.coopera.service.RegistryService;
import com.tlgen.coopera.utils.HttpUtils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class RegistryServiceImpl implements RegistryService {

    @Value("${spring.cloud.coopera.discovery.address}")
    private String cooperaAddress;

    @Autowired
    private Environment environment;

    @Override
    public void selectServerList() {
        String url = "http://" + cooperaAddress + "/registry/select";
        Call call = new OkHttpClient().newBuilder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .build().newCall(new Request.Builder()
                        .url(url)
                        .get()
                        .build());
        try {
            Response response = call.execute();
            assert response.body() != null;
            System.out.println(response.body().string());
            System.out.println("获取服务列表成功!");
        } catch (IOException e) {
            System.out.println("获取服务列表失败!");
        }
    }

    @Override
    public void doRegistry() {
        String absolutePath = System.getProperty("user.dir");
        String applicationName = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1);
        String serverIp = HttpUtils.selectLocalIp();
        Integer port = Integer.valueOf(Optional.ofNullable(environment.getProperty("server.port"))
                .orElse("8080"));
        String serverName = Optional.ofNullable(environment.getProperty("spring.application.name"))
                .orElse(applicationName);
        String url = "http://" + cooperaAddress + "/registry/doRegistry";
        Call call = new OkHttpClient().newBuilder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .build().newCall(new Request.Builder()
                        .url(url)
                        .post(RequestBody.create(
                                MediaType.parse("application/json; charset=utf-8"),
                                JSONObject.toJSONString(RegistryServer.builder()
                                        .ip(serverIp)
                                        .port(port)
                                        .name(serverName)
                                        .build())))
                        .build());
        try {
            Response response = call.execute();
            assert response.body() != null;
            String result = response.body().string();
            if (result.contains("SUCCESS"))
                System.out.println("服务注册成功!");
        } catch (IOException e) {
            System.out.println("服务注册失败!");
        }
    }

}
